import axios from 'axios'
const instance = axios.create()  // 创建axios实例
import qs from 'qs'
import 'vant/es/toast/style';
import { Toast } from 'vant';
interface Response {
    code: number;
    msg: string;
    data?: any;
}

const myaxios = {
    /** 用于发送get请求 
     *  url: 请求资源路径  
     *  params: 请求参数（Object形式）
     */
    get(url: string, params?: object): Promise<Response> {
        Toast.loading({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        return new Promise((resolve, reject) => {
            instance({
                url,
                method: 'get',
                params
            }).then((res: any) => {
                resolve(res);
                Toast.clear();
            }).catch(err => {
                Toast.fail('网络异常,稍后重试')
            })
        })
    },

    /**
     * 用于发送post请求
     * @param {String} url   请求资源路径
     * @param {Object} params   请求参数（对象类型）
     * @returns Promise<Response>
     */
    post(url: string, params?: object): Promise<Response> {
        return new Promise((resolve, reject) => {
            instance({
                url,
                method: 'post',
                data: qs.stringify(params)
            }).then((res: any) => {
                resolve(res);
                Toast.clear();
            }).catch(err => {
                Toast.fail('网络异常,稍后重试')
            })
        })
    }
}

export default myaxios